package cn.edu.sdjzu.xg.eagle.Controller;

import cn.edu.sdjzu.xg.eagle.Service.SchoolService;
import cn.edu.sdjzu.xg.eagle.Service.UserService;
import cn.edu.sdjzu.xg.eagle.entity.User;
import cn.edu.sdjzu.xg.eagle.exception.BaseException;
import cn.edu.sdjzu.xg.eagle.factory.ServiceFactory;
import cn.edu.sdjzu.xg.eagle.util.JSONUtil;
import com.alibaba.fastjson2.JSONObject;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.sql.SQLException;


@WebServlet("/login")
public class LoginCtl extends HttpServlet {

    private UserService userService;

    public void init() throws ServletException {
        try {
            // 获取service实例对象
            userService = ServiceFactory.getService(UserService.class,"UserService");
        } catch (BaseException e) {
            throw new ServletException("初始化UserService失败:" + e.getMessage());
        }
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {

        request.setCharacterEncoding("utf-8");
        String userJson = JSONUtil.getJSON(request);

        User userToLogin = JSONObject.parseObject(userJson, User.class);

        JSONObject message = new JSONObject();

        try {
            userService.login(userToLogin);

            if (userToLogin.getId() == null) {
                message.put("message","用户id不存在/密码错误");
                message.put("code",500);
            } else {
                message.put("message","登录成功");
                message.put("code",200);

            }
        } catch (SQLException e) {
            message.put("message","数据库异常");
        } catch (Exception e) {
            message.put("message","网络异常");
        }

        response.setContentType("application/json;charset=utf-8");
        response.getWriter().println(message.toJSONString());

    }
}
